from fastapi import FastAPI, status

app = FastAPI()

# 1. Path Parameters

# @app.get("/items/{item_id}")
# async def read_item(item_id):
#     return {"item_id": item_id}


# 2. Path Parameters with Type Conversion
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}


# 3. Query Parameters (声明的参数不是路径参数时，路径操作函数会把该参数自动解释为查询参数。)
# http://127.0.0.1:8000/items/
# http://127.0.0.1:8000/items/?skip=0&limit=10
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]


# 4. Optional Parameters
@app.get("/items2/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}


# 5. Required Query Parameters
@app.get("/items3/{item_id}")
async def read_user_item(item_id: str, needy: str):
    item = {"item_id": item_id, "needy": needy}
    return item


# 6. Request Body
from pydantic import BaseModel, EmailStr


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


@app.post("/items4/")
async def create_item(item: Item):
    return item


from typing import Any


# 7. Response Model
@app.get("/items5/", response_model=list[Item])
async def read_items() -> Any:
    return [
        {"name": "Portal Gun", "price": 42.0},
        {"name": "Plumbus", "price": 32.0},
    ]


from typing import Union


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: str | None = None


class UserOut(BaseModel):
    username: str
    email: EmailStr
    full_name: str | None = None


# 8. Input and Output Models
@app.post("/user/", response_model=UserOut)
async def create_user(user: UserIn) -> Any:
    return user


# 9. Response Status Code
@app.post("/items6/", status_code=201)
async def create_item(name: str):
    return {"name": name}
